<?php

namespace app\api\controller;

use app\common\controller\UtilController;
use app\common\model\Member;
use app\common\model\TestLog;
use app\common\model\TopicLog;
use think\Cache;
use think\Controller;
use think\Db;
use think\Request;
use think\Response;
use traits\think\Instance;

class TopicController extends Controller
{
    /**
     * 显示资源列表
     *
     * @return \think\Response
     */
    public function index()
    {
        //
    }

    /**
     * 显示创建资源表单页.
     *
     * @return \think\Response
     */
    public function create()
    {
        //
    }

    public function getTopic(){
        $topic = Db::table('jht_topic')->where('status=1')->order('createdate','desc')->field('id')->find();
        if ($topic){
            return $topic['id'];
        }else{
            return false;
        }
    }

    /**
     * 保存新建的资源
     *
     * @param  \think\Request  $request
     * @return \think\Response  分数,等级
     */
    public function save(Request $request)
    {
        $req = Request::instance()->post('answer');
        $token = Request::instance()->post('token');
        $arr = json_decode($req,true);
        $asset = Request::instance()->post('asset');
        $revenue = Request::instance()->post('revenue');
        
      //  $arr = $req;
//         $result = $arr['result'];
  //     return $this->response(['Data'=>$result]);
        $userinfo = $this->tokenFindUser($token);
        if (!$userinfo) return $this->response((['Success'=>false,'Msg'=>'身份认证失败']));
        $score = 0;  //分数
        //$userinfo
        $log_id =  UtilController::getSignature($userinfo['uid'],time());
        $userinfo['topic'] = $this->getTopic();

        try{
            $topicLogModel = new TopicLog();
            $topic_log_all = [];
            foreach ($arr as $vo){
                $item['tid'] = $userinfo['topic'];
                $item['uid'] = $userinfo['uid'];
                $item['answer'] = $vo['option_id'];
                $item['qsort'] = $vo['question_id'];
                $item['score'] = $vo['score'];
                $item['log_id'] =$log_id;
                $score = $score + $item['score'];
                array_push($topic_log_all,$item);
            }
            

            $IsSave = $topicLogModel->saveAll($topic_log_all);
            $level_data = $this->ScoreToLevel($score);
            $jht_testlog = new TestLog();
            $testlog_data = [
                'pid' => $userinfo['topic'],//试卷id
                'uid' => $userinfo['uid'],//用户id
                'score' => $score,//分数
                'level' => $level_data['level'],
                'log_id' => $log_id,
                'createdate' => date('Y-m-d H:i:s',time()),
            ];
            $jht_testlog->save($testlog_data);
            //用户保存  level
            $user = new Member();
            $user->where('id='.$userinfo['uid'])->update([
                'level' => $level_data['level'],
                'updatetime' => date('Y-m-d H:i:s',time()),
                'asset' => $asset,
                'revenue' => $revenue,
            	'ismember' =>1				
            ]);

            $level_data['score'] = $score;
            return $this->response((['Success'=>true,'Msg'=>'提交成功','Data'=>$level_data]));
        }catch (\Exception $e){
            return $this->response((['Success'=>false,'Msg'=>'失败','Data'=>$e]));
        }
    }

    function condition(){
        $request = Request::instance();
        if ($request->isPost()){
            $token = $request->param('token');
            if($token = Cache::get($token)){
                $member = new Member();
                $asset = $request->param('asset');
                $revenue = $request->param('revenue');
                if($asset==0 && $revenue==0) return $this->response(['Success'=>false,'Msg'=>'必须选择一项','Data'=>[]]);
                $res = $member->update([
                    'asset' => $asset,
                    'revenue' => $revenue,
                ],['id'=>$token['uid']]);
                if ($res)  return $this->response(['Success'=>true,'Msg'=>'资产收入确认成功','Data'=>[]]);
                else return $this->response(['Success'=>false,'Msg'=>'资产收入确认失败','Data'=>[]]);
            }else{
                return $this->response(['Success'=>false,'Msg'=>'认证失败','Data'=>[]]);
            }
        }
    }
    

    // 通过token获取用户
    protected function tokenFindUser($token){
        if (Cache::get($token)){
            $user_info = Cache::get($token);
            return $user_info;
        }else{
            return false;
        }
    }

    protected function ScoreToLevel($score){
        $level_data = [
            'level' => 1,
            'type' => '保守型',
            'bear' => '较低',
        ];
        //风险类型
        //风险承受能力
        //适合产品
        switch ($score){
            case $score <= 20:  // 保守型  极低  低风险
                $level_data['level'] = 1;
                $level_data['type'] = '保守型';
                $level_data['bear'] = '极低';
                break;
            case $score > 20 && $score <= 40:  // 稳健性  较低  中低分析
                $level_data['level'] = 2;
                $level_data['type'] = '稳健性';
                $level_data['bear'] = '较低';
                break;
            case $score > 40 && $score <= 60:  // 平衡型  一般  中风险
                $level_data['level'] = 3;
                $level_data['type'] = '平衡型';
                $level_data['bear'] = '一般';
                break;
            case $score > 60 && $score <= 80:  // 成长型  较高  中低风险
                $level_data['level'] = 4;
                $level_data['type'] = '成长型';
                $level_data['bear'] = '较高';
                break;
            case $score > 80 && $score <= 100:  // 进取型  极高  高风险
                $level_data['level'] = 5;
                $level_data['type'] = '进取型';
                $level_data['bear'] = '极高';
                break;
        }
        return $level_data;
    }

    /**
     * 显示指定的资源
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function read($id)
    {
        $res = Db::table('jht_question')->alias('a')
            ->join(['topic'=>'b','jht_'],'a.pid = b.id','left')
            ->field("a.id,a.title,a.typetitle")
            ->order('a.qsort')
            ->where('b.id ='.$id)
            ->select();

        foreach ($res as &$v){
            $options = Db::table('jht_option')->field('id,qsort,title,score,sort')->order('sort')->where('qsort='.$v['id'])->select();
            $v['options'] = $options;
        }
        if ($res){
           // return jsonp((['Success'=>true,'Msg'=>'获取成功','data'=>$res]));
            return $this->response((['Success'=>true,'Msg'=>'获取成功','Data'=>$res]));
        }else{
          //  return json((['Success'=>true,'Msg'=>'获取失败','data'=>$res]));
            return $this->response((['Success'=>false,'Msg'=>'获取失败','Data'=>$res]));
        }
    }

    /**
     * 显示编辑资源表单页.
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function edit($id)
    {
        //
    }

    /**
     * 保存更新的资源
     *
     * @param  \think\Request  $request
     * @param  int  $id
     * @return \think\Response
     */
    public function update(Request $request, $id)
    {
        //
    }

    /**
     * 删除指定资源
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function delete($id)
    {
        //
    }

    protected function response($data, $type = 'json', $code = 200)
    {
        return Response::create($data, $type,200,['Access-Control-Allow-Origin'=>'*'])->code($code);
    }
}
